/**
 * Created by LXhan on 2017/11/20.
 */
var tableWater;//水表
var activebuildingID = '';//选中楼宇ID
var code = '';//查询条件编号
var time = getNowFormatDate();//查询条件日期
var today = DateUtils.dateFormat(new Date(), "yyyy-MM"); // 今天的日期
var displaySwitch = 0;//显示隐藏开关
var $;
var table
layui.use(['jquery', 'table', 'laydate', 'form', 'layer', 'element','treeGrid'], function () {
    table = layui.table;
    var form = layui.form;
    var element = layui.element;
    treeGrid = layui.treeGrid;
    $ = layui.jquery;
    var laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
        elem: '#waterdate'
        , type: 'month'
        , trigger: 'click'
        , btns: ['now', 'confirm']
        , done: function (value, date, endDate) {
            $("#waterdate").val(value);
            search(1);
        }
    });
    $("#waterdate").val(today);
    activebuildingID = QueryUtils.GetQueryString('activebuildingID');
    BUSINESS_ID=QueryUtils.GetQueryString("activebusinessID");
    <!--**********************水电表管理*************************-->

    //水表展示已知数据
    tableWater = treeGrid.render({
        elem: '#sbgl'
        , url: '/hydropowerdetail/list'
        , where: {type: 'ae5806f8184546208411b99e6117eaa2'}
        , cellMinWidth: 100
        , treeId: 'ID'//树形id字段名称
        , treeUpId: 'PID'//树形父id字段名称
        , treeShowName: 'CODE'//以树形式显示的字段
        , cols: [[
            /*{type: 'checkbox'},*/
            {checkbox: true, LAY_CHECKED: true} //默认全选
            ,{field: 'CODE', width: '300', title: '水表编号'}
            , {field: 'NAME', width: '300', title: '水表位置', templet: '#nameTpl'}
            , {field: 'ATTR', width: '100', title: '水表属性', align: 'center', templet: '#attrTpl'}
            , {field: 'CUR_DEGREES', title: '本次读数',edit: 'text', width: 150, style: 'cursor: pointer;', templet: '#emptyTemp'}
            , {field: 'CUR_DATE', title: '本次读表日期', width: 150, templet: '#curDate'}
            , {fixed: 'right', title: '操作', width: 80, align: 'right', toolbar: '#sbglBar'}
        ]]
        , id: 'WT'
        , page: true
        , height: 470
        , done: function (res, curr, count) {
            setGenRecordDisplayWater(count);
            var list = res.data;
            $.each(list, function (i, item) {
                if (item.IS_BILL == 1) {
                    item.edit = false;
                } else {
                    item.edit = true;
                }
            })
            //TODO:设置可编辑单元格
            setEditEnable({
                data: list,//表格列表数据
                editConditions: "edit",//数据源中标识可编辑的字段
                rowKey: "CODE",//数据源中查找行的标识字段（对应表头）
                column: "CUR_DEGREES"//可编辑的字段，表格列（对应表头）
            });
            var chooseDay = $("#waterdate").val();
            var days = DateUtils.getDaysOfMonth(chooseDay.substring(0, 4), chooseDay.substring(5, 7));
            $('.cur-date').each(function () {
                var _obj = this;
                laydate.render({
                    elem: this
                    , min: chooseDay + '-01'
                    , max: chooseDay + '-' + days
                    , trigger: 'click',
                    done: function (value) {
                        var eid = $(_obj).attr("eid");
                        var id = $(_obj).attr("id");
                        var read = $(_obj.parentNode.parentNode.parentNode.parentNode).find("td").eq(4).find("div").find("p").html();
                        var lastDate = $(_obj.parentNode.parentNode.parentNode).find("td").eq(5).find("div").html();
                        var initDate = $(_obj).attr("value");
                        editCurDegrees(id, id, read, value, lastDate, initDate, $(_obj));
                    }
                });
            });
        }
    });
    //打开抄表记录页面
    treeGrid.on('tool(water)', function (obj) {
        var data = obj.data;
        //生成账单
        if (obj.event === 'genRecord') {
            parent.layer.open({
                type: 2
                , zIndex: 1001
                ,closeBtn :0//不显示关闭按钮
                , anim: 7
                , offset: 'r'
                , shadeClose: true
                , area: ['70%', '100%']
                , content: '../../../webhtml/hydropower/eletric_info.html?CODE='+data.ID+''//这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                , yes: function (index, layero) {
                    //do something
                    //layer.closeAll();
                    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                    parent.layer.close(index);
                }
            });
        }
    });

    //编辑水表
    table.on("edit(water)", function (obj) {
        editCurDegrees(obj.data.EID, obj.data.ID, obj.value, '');
    });

    //table监听事件

    table.on('tool(water)', function (obj) {
        var data = obj.data;
        if (obj.event === 'genRecord') {
            var data = genBill(data.EID, data.TYPE, data.CUR_DATE);
            if (data.errcode == "00") {
                tableWater.reload();
            } else {
                layer.msg(data.errmsg);
            }
        }
    });


});

//水表生成记录按钮
function genWaterRecord() {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genrocord",
        async: true,
        data: {
            type: 'ae5806f8184546208411b99e6117eaa2',
            buildingId: activebuildingID
        },
        success: function (rs) {
            tableWater.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

/*
 批量生成账单水表
 */
function genWaterBillMany() {
    var data = table.checkStatus('WT').data;
    var pd = initDatas(data);
    genBillMany(pd);
    tableWater.reload();
}

//水电表查询按钮
function search(type) {
    displaySwitch = 1;
    if (type == 0) {
        code = $("#elecode").val();
        time = $("#eledate").val();
        if (time.length > 0) {
            time += '-' + '01'
        } else {
            time = getNowFormatDate();
        }
        tableEle.reload({
            where: {type: 'b938139a48ed4344a11a7180b48eede6', buildingId: activebuildingID, code: code, time: time}
        });
    } else {
        code = $("#watercode").val();
        time = $("#waterdate").val();
        if (time.length > 0) {
            time += '-' + '01'
        } else {
            time = getNowFormatDate();
        }
        tableWater.reload({
            where: {type: 'ae5806f8184546208411b99e6117eaa2', buildingId: activebuildingID, code: code, time: time}
        });
    }
}

/*生成本月水表抄表记录按钮是否显示*/
function setGenRecordDisplayWater(count) {
    if (count > 0) {
        // $("#genWaterRecord").hide();
        $("#genWaterBillMany").show();
    } else {
        // $("#genWaterRecord").show();
        $("#genWaterBillMany").hide();
    }
}

//修改当前读数
function editCurDegrees(eid, id, curDegrees, curDate, lastDate, initDate, obj) {
    if (!curDegrees) {
        layer.msg("请先填写读数");
        obj.val("");
        return false;
    }
    if (!!lastDate) {
        var o = DateUtils.compareTime(curDate, lastDate);
        if (o < 0) {
            layer.msg("当前读数日期需大于等于上次读数日期");
            obj.val(initDate);
            return false;
        }
    }

    //询问框
    layer.confirm('本期读数:'+curDegrees+',抄表时间:' + curDate+'', {
        btn: ['确定','取消'] //按钮
    }, function(){
        //修改当前读数 存一下当前的月时间标识
        $.ajax({
            type: "post",
            url: "/hydropowerdetail/edit",
            async: true,
            data: {
                eid: eid,
                id: id,
                curDegrees: curDegrees,
                curDate: curDate,
                req_month: $("#eledate").val()
            },
            success: function (rs) {
                if (curDate != null && curDate.length > 0) {
                    layer.alert(rs.errmsg);
                    $(".layui-laypage-btn")[0].click();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }, function(){

    });

}


//生成账单
function genBill(eid, type, time) {
    var result;
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genbillnew",
        async: false,
        data: {
            eid: eid,
            type: type,
            time: time
        },
        success: function (rs) {
            result = rs;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
    return result;
}

//批量生成账单封装数据
function initDatas(data) {
    var rs;
    $.each(data, function (i, info) {
        if (info.IS_BILL != 1) {
            if (rs == null) {
                rs = info.EID + "," + info.TYPE + "," + info.CUR_DATE;
            } else {
                rs += "#" + info.EID + "," + info.TYPE + "," + info.CUR_DATE;
            }
        }

    })
    return rs;
}

/*
 批量生成账单
 */
function genBillMany(pd) {
    $.ajax({
        type: "post",
        url: "/hydropowerdetail/genbillmanynew",
        async: false,
        data: {
            data: pd
        },
        success: function (rs) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    // + " " + date.getHours() + seperator2 + date.getMinutes()
    // + seperator2 + date.getSeconds();
    // var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    //     + " " + date.getHours() + seperator2 + date.getMinutes()
    //     + seperator2 + date.getSeconds();
    return currentdate;
}


//**************************************************************************************//

// region 获取可编辑的单元格
/**
 * 获取可编辑的单元格
 *
 * @param {object} option
 * {
   *    data: 表格数据源
   *    editConditions: 数据源中判断是否可编辑的字段
   *    rowKey: 可编辑单元格所在行的唯一标示字段
   *    column: 可编辑单元格所在的列
   * }
 */
function setEditEnable(option) {
    // region 可编辑单元格相关数据
    var editCellInfo = {
        rows: [],
        selectors: []
    };
    // endregion

    var config = {
        data: option.data || [],
        editConditions: option.editConditions || "",
        rowKey: option.rowKey || "",
        column: option.column || ""
    };
    config.data.map(function (item) {
        if (item[config.editConditions]) {
            editCellInfo.rows.push(item);
            editCellInfo.selectors.push('td[data-field="' + (config.rowKey) + '"][data-content="' + item[config.rowKey] + '"]');
        }
    });
    $(editCellInfo.selectors.join(","))
        .closest("tr")
        .find('[data-field="' + config.column + '"]')
        .attr("data-edit", true);

    // console.log('可编辑元素所在行=>',editCellInfo.selectors)
    // console.log('可编辑元素=>',$(editCellInfo.selectors.join(",")).closest("tr").find('[data-field="' + config.column + '"]'))

    // region 键盘事件监听
    window.addEventListener('keyup', function (event) {
        // console.log(event.keyCode,event)//下 40 上 38 tab 9
        if (event.keyCode === 40 || event.keyCode === 38) {
            var $eventRow = $(event.target).closest('tr');
            var dataContent = $eventRow.find('td[data-field="' + (config.rowKey || "ID") + '"]').attr('data-content');
            var index = editCellInfo.selectors.indexOf('td[data-field="' + (config.rowKey || "ID") + '"][data-content="' + dataContent + '"]');
            (index < 0 && (index = editCellInfo.selectors.length - 1)) || (index > editCellInfo.selectors.length - 1 && (index = 0));
            $(event.target).blur();
            $(editCellInfo.selectors[index + ((event.keyCode === 40 && 1) || (event.keyCode === 38 && -1))]).siblings('[data-field="' + config.column + '"]').click().find('.layui-table-edit').focus();
        }
    });
}
